import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { setToken, loadTokenFromStorage } from '@/store/authSlice';
import {
  Button,
  TextField,
  Paper,
  Typography,
  Container,
  Box,
  CircularProgress,
  Snackbar,
  Alert,
  Grow,
  Tabs,
  Tab
} from '@mui/material';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import { login, register, checkAccountExists, checkUsernameExists } from '@/apis/login';
import { useNotification } from '@/context/NotificationContext'; // 导入 useNotification hook

function GrowTransition(props) {
  return <Grow {...props} />;
}

export default function AuthPage() {
  const [account, setAccount] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const [tabValue, setTabValue] = useState(0);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { login: notificationLogin } = useNotification(); // 使用 useNotification hook

  useEffect(() => {
    dispatch(loadTokenFromStorage());
  }, [dispatch]);

  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
    setError('');
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setError('');
    setIsLoading(true);

    try {
      let userInfo;
      if (tabValue === 0) {
        // 登录
        userInfo = await login(account, password);
        console.log('登录成功，用户信息:', userInfo);
      } else {
        // 注册
        const accountExists = await checkAccountExists(account);
        const usernameExists = await checkUsernameExists(username);
        
        if (accountExists) {
          throw new Error('该账号已被注册');
        }
        if (usernameExists) {
          throw new Error('该用户名已被使用');
        }
        
        userInfo = await register({ account, password, username });
        console.log('注册成功，用户信息:', userInfo);
      }
      
      if (userInfo && userInfo.token) {
        dispatch(setToken({
          token: userInfo.token,
          account: userInfo.account,
          role: userInfo.role,
          username: userInfo.username,
          createdAt: userInfo.createdAt,
          userId: userInfo.userId
        }));
        notificationLogin(); // 调用 NotificationContext 的 login 函数
        setSnackbar({ open: true, message: tabValue === 0 ? '登录成功！' : '注册成功！', severity: 'success' });
        setTimeout(() => navigate('/home'), 1500);
      } else {
        throw new Error('操作失败，请重试');
      }
    } catch (err) {
      console.error('错误:', err.response ? err.response.data : err.message);
      const errorMessage = err.response?.data?.message || err.message || '操作失败，请重试';
      setError(errorMessage);
      setSnackbar({ open: true, message: errorMessage, severity: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCloseSnackbar = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setSnackbar({ ...snackbar, open: false });
  };

  return (
    <Container component="main" maxWidth="xs">
      <Paper 
        elevation={3} 
        sx={{
          marginTop: 30,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          padding: 3,
        }}
      >
        {tabValue === 0 ? 
          <LockOutlinedIcon sx={{ m: 1, bgcolor: 'primary.main', color: 'white', p: 1, borderRadius: '50%' }} /> :
          <PersonAddIcon sx={{ m: 1, bgcolor: 'primary.main', color: 'white', p: 1, borderRadius: '50%' }} />
        }
        <Tabs value={tabValue} onChange={handleTabChange} sx={{ mb: 2 }}>
          <Tab label="登录" />
          <Tab label="注册" />
        </Tabs>
        <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
          <TextField
            margin="normal"
            required
            fullWidth
            id="account"
            label="账号"
            name="account"
            autoComplete="account"
            autoFocus
            value={account}
            onChange={(e) => setAccount(e.target.value)}
          />
          {tabValue === 1 && (
            <TextField
              margin="normal"
              required
              fullWidth
              id="username"
              label="用户名"
              name="username"
              autoComplete="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
            />
          )}
          <TextField
            margin="normal"
            required
            fullWidth
            name="password"
            label="密码"
            type="password"
            id="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          {error && (
            <Typography color="error" variant="body2" sx={{ mt: 1 }}>
              {error}
            </Typography>
          )}
          <Button
            type="submit"
            fullWidth
            variant="contained"
            sx={{ mt: 3, mb: 2 }}
            disabled={isLoading}
          >
            {isLoading ? <CircularProgress size={24} /> : (tabValue === 0 ? '登录' : '注册')}
          </Button>
        </Box>
      </Paper>
      <Snackbar
        open={snackbar.open}
        autoHideDuration={2000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        TransitionComponent={GrowTransition}      
      >
        <Alert onClose={handleCloseSnackbar} severity={snackbar.severity} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
}